package sunsun.xiaoli.jiarebang.utils;

import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.itboye.pondteam.utils.loadingutil.MAlert;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

/***
 * 功能：用线程保存图片
 *
 * @author wangyp
 */
public class SaveImage extends AsyncTask<String, Void, String> {
    String imgurl = "";
    Handler handler;

    public SaveImage(String imgurl, Handler handler) {
        this.imgurl = imgurl;
        this.handler = handler;
    }

    @Override
    protected String doInBackground(String... params) {
        String result = "";
        try {
            String sdcard = Environment.getExternalStorageDirectory().toString();
            File file = new File(sdcard + "/Download");
            if (!file.exists()) {
                file.mkdirs();
            }
            int idx = imgurl.lastIndexOf(".");
            String ext = imgurl.substring(idx);
            file = new File(sdcard + "/Download/" + new Date().getTime() + ext);
            InputStream inputStream = null;
            URL url = new URL(imgurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(20000);
            int maxSize = conn.getContentLength();
            if (conn.getResponseCode() == 200) {
                inputStream = conn.getInputStream();
            }
            byte[] buffer = new byte[4096];
            int len = 0;
            //该线程已经下载数据的长度
            int total = 0;
            FileOutputStream outStream = new FileOutputStream(file);
            while ((len = inputStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
                total += len;
                Log.i("iSpring", "DownloadTask -> onPostExecute, Thread name: len:" + total + "    maxSize:" + maxSize + " buffer:" + buffer.length);
                Message message = null;
                if (total >= maxSize) {
                    message = Message.obtain(handler, 2, total, maxSize);
                } else {
                    message = Message.obtain(handler, 1, total, maxSize);
                }
                message.sendToTarget();
            }
            outStream.close();
            result = "图片已保存至：" + file.getAbsolutePath();
        } catch (Exception e) {
            result = "保存失败！" + e.getLocalizedMessage();
            Message message = Message.obtain(handler, 3, -1, -1, result);
            message.sendToTarget();

        }
        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        MAlert.alert(result);
//        showToast(result);
    }
}